<?php

/**
 * Ignus Framework
 *
 * @author Sergey Palyanov <sergey.palyanov@gmail.com>
 * @link http://code.google.com/p/ignus-php/
 * @license http://apache.org/licenses/LICENSE-2.0
 * @package Ignus
 * @subpackage App
 * @since 0.1
 */

namespace Ignus;

/**
 * @package Ignus
 * @subpackage App
 * @since 0.3
 */
abstract class EntityManager
{
    /**
     * Connection string
     * @var string
     * @since 0.4.2
     */
    private static $dsn;

    /**
     * Connection options
     * @var array
     * @since 0.4.2
     */
    private static $options;

    /**
     * Database driver class
     * @var string
     * @since 0.4.2
     */
    private static $class;

    /**
     * @var Driver Database handler object
     */
    private static $connection = null;

    /**
     * Initialize manager with database connection data
     * @static
     * @param string $driver Driver class name
     * @param string $dsn Database connections string
     * @param array $options Connection options array
     * @return void
     */
    public static function init($driver, $dsn, $options = array())
    {
        $class = ucfirst($driver);
        self::$class = 'Ignus\Db\\' . $class . '\\' . $class;

        self::$dsn = $dsn;
        self::$options = $options;
    }

    /**
     * Establishes connection to database driver
     * @static
     * @return void
     * @since 0.4.2
     */
    private static function connect()
    {
        if (!class_exists(self::$class, true))
            throw new \RuntimeException('Database driver class \''.self::$class.'\' does not exists');

        self::$connection = new self::$class();
        self::$connection->connect(self::$dsn, self::$options);
    }

    /**
     * Performs establishing connection on first invocation
     * @static
     * @return Db\Driver Database connection
     */
    public static function getConnection()
    {
        if (self::$connection == null)
            self::connect();

        return self::$connection;
    }
}
